package org.example;

import okhttp3.*;
import org.example.yulinwumei.WuMei_XiaoShou;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SalesClient {
    private static final Logger logger = LoggerFactory.getLogger(SalesClient.class);
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static OkHttpClient client = new OkHttpClient();
    public static String baseUrl = "http://www.wuhuishipin.cn/api/xiaoshoujilu.php";

    // 通用POST请求方法
    public static boolean postRequest(JSONArray data, String quYu, String date) throws IOException {
        JSONObject requestBody = new JSONObject();
        requestBody.put("token", "8");
        requestBody.put("action", "create");
        requestBody.put("data", data);
        logger.info("[前端提交] "+ quYu + "提交了：" + data.length() + " 条 " + date + " 的记录");

        RequestBody body = RequestBody.create(requestBody.toString(), JSON);
        Request request = new Request.Builder()
                .url(baseUrl)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            JSONObject createResponse = new JSONObject(response.body().string());

            // 增强解析逻辑
            String message = createResponse.optString("message", "");
            int code = createResponse.optInt("code", -1);
            int insertedCount = parseInsertCount(message, code);

            int total = data.length();
            int duplicateCount = total - insertedCount;

            String logDetail = String.format("[后端返回] " + "%s提交%s记录：总数%d ▶ 成功%d条（%.1f%%）| 重复%d条（%.1f%%）",
                    quYu, date, total, insertedCount,
                    (insertedCount*100.0/total),
                    duplicateCount,
                    (duplicateCount*100.0/total));

            logger.info(logDetail);
            return true;
        }
    }

    private static int parseInsertCount(String message, int code) {
        // 处理无新增记录的情况
        if (message.contains("无新增记录")) {
            return 0; // 明确返回0
        }

        Pattern pattern = Pattern.compile("成功创建\\s*(\\d+)\\s*条(?:记录)?"); // 增强正则匹配
        Matcher matcher = pattern.matcher(message);

        if (code == 201) {
            if (matcher.find()) {
                try {
                    return Integer.parseInt(matcher.group(1));
                } catch (NumberFormatException e) {
                    logger.warn("[数据异常] 数值解析失败 | 原始消息：{}", message); // 使用SLF4J占位符
                }
            } else {
                logger.warn("[协议异常] 未匹配到数量 | 完整响应：{}", message);
            }
        }
        return 0;
    }

}
